package main

import (
	"questionnaire-gen/backend"
	"fmt"
	"log"
	//"os"
	"net/http"
	//amber "github.com/eknkc/amber"
	"github.com/gorilla/mux"
	"html/template"
	text "text/template"
	"encoding/json"
	//"gopkg.in/mgo.v2"
	//"gopkg.in/mgo.v2/bson"
	"github.com/gorilla/sessions"
	"flag"

//	"code.google.com/p/gofpdf"
)

var(
	//tpls map[string]template.Template
	//options = amber.Options{true, false}
	CompiledTemplates map[string]*template.Template
	CompileTpls bool = false
	//MangoSession *mgo.Session
	//TestDB mgo.Database
	webDir *string = new(string)
    ApplicationContext *AppContext
    adminEmail = new(string); adminPass = new(string)
)

//compile template file (tplFile) and write result back to ResponseWriter

//func reply(w *http.ResponseWriter, tplFile string, params map[string]interface{} ) error {
//	cmp := amber.New()
//	//err := cmp.ParseFile("templates/partials/template.amber")
//	err := cmp.ParseFile(tplFile)
//	//data, err := cmp.CompileString()
//	//fmt.Println(data)
//	//return cmp.CompileWriter(*w)
//
//	t := template.New("test")
//	//t , err = t.Parse(data)
//	t , err = t.Parse("<html><body><h1 a='asfsdf'>myyyy</h1></body></html>")
//	if err != nil{
//		fmt.Println("###Error: " , err)
//	}
//
//
//	t.Execute(os.Stdout, nil)
//	fmt.Println("template executed")
//
//	/*
//	*/
//	t, err = amber.CompileFile(tplFile, options)
//	if err != nil{
//		log.Fatalf("Error compiling tplFile %s, %v", tplFile, err)
//		return err
//	}
//	t.Delims("<<<", ">>>")
//
//	return t.Execute(*w, params)
//}

func init(){
	
	flag.StringVar(webDir, "webdir", "../web", "Web directory contains static and html files")
	flag.StringVar(adminEmail, "adminName", "admin@eg.ibm.com", "Admin email")
	flag.StringVar(adminPass, "adminPass", "pass", "Admin password")
	flag.Parse()


    ApplicationContext = &AppContext{
        AdminEmail:*adminEmail, AdminPassword: *adminPass, 
        MongoSession: backend.MongoSession, store: sessions.NewCookieStore([]byte("my secret key")),
    }

}

func webPath(dir string) string{
	return *webDir + dir
}


func main(){
	//prepare DB connection and mocks
	sess := backend.Connect("localhost")
	defer sess.Close()
	backend.MongoMocks()

	fsStatics := http.FileServer(http.Dir(webPath("/static")))
	fsPartials := http.FileServer(http.Dir(webPath("/templates/partials")))

	r := mux.NewRouter()

	r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fsStatics))
	r.PathPrefix("/part/{partial}").Handler(http.StripPrefix("/part/", fsPartials))

	get := r.Methods("GET").Subrouter()
	get.Handle("/", myHandlerFunc(index))
	get.HandleFunc("/template/{uid}", questionnaire)
	//get.HandleFunc("/view/{partial}", parsePartial) // used by amber
	get.Handle("/auth/user", myHandlerFunc(auth))
	get.HandleFunc("/db/addTpl", addTemplate)
	get.HandleFunc("/db/getTpl", getTemplate)
	get.HandleFunc("/db/updateTpl", updateTemplate)
	get.Handle("/test/auth",myHandlerFunc(testAuth).Auth())
//	get.Handle("/admin/cmd", myHandlerFunc(adminCmd))


	//post := r.Headers("Content-Type","application/json").Methods("POST").Subrouter()
	post := r.Methods("POST").Subrouter()
	post.Handle("/login", myHandlerFunc(login))
	post.Handle("/logout", myHandlerFunc(logout))
	post.HandleFunc("/blog/cmd", blogCmd)
	post.HandleFunc("/tpl/cmd", tplCmd)
	//post.Handle("/admin/cmd", myHandlerFunc(adminCmd))
	post.HandleFunc("/admin/cmd", AdminCommands)
	
	http.Handle("/", myHandler(r))

	fmt.Println("Listening to port 9090")
	http.ListenAndServe(":9090", nil)
}


func blogCmd(w http.ResponseWriter, r *http.Request){
	var cmd = new(backend.JsonCommand)
	err := json.NewDecoder(r.Body).Decode(cmd) 
	if err != nil {log.Fatal("failed parsing blog cmd: " , err)}

	w.Header().Add("Content-Type", "application/json")

	//json.NewEncoder(w).Encode(cmd)
	w.Write([]byte("{ \"data\":"))
	json.NewEncoder(w).Encode(backend.DefaultPosts)
	w.Write([]byte("}"))
}

func tplCmd(w http.ResponseWriter, r *http.Request){
	var cmd = new(backend.JsonCommand)
	err := json.NewDecoder(r.Body).Decode(cmd) 
	if err != nil {log.Fatal("failed parsing blog cmd: " , err)}

	//json.NewEncoder(w).Encode(cmd)
	w.Write([]byte("{ \"data\":"))
	json.NewEncoder(w).Encode(cmd.Data)
	w.Write([]byte("}"))

}

//func parsePartial(w http.ResponseWriter, r *http.Request){
//	vars := mux.Vars(r)
//	partial := fmt.Sprintf("./templates/partials/%s.amber", vars["partial"])
//
//	t, err := amber.CompileFile(partial, options)
//	if err != nil {log.Fatal(err)}
//	t.Execute(w, nil)
//
////	http.ServeFile(w, r, partial)
//}

var store = sessions.NewCookieStore([]byte("my secret key"))

//func index(w http.ResponseWriter, r *http.Request){

func index(w http.ResponseWriter, r *http.Request, c *AppContext, rc *ReqContext) error{
	//t := text.New("basic")
	//t, err := t.Parse("<html><body>empty</body></html>")
	//t, err := t.ParseFiles("./templates/layout/basic.html")
	//t, err := text.ParseFiles("/home/sam/src/dev/go/src/github.com/samnut2/sampleweb/test.html")

    /*
	s, _ := c.store.Get(r, "user")
    s.Values["email"] = "b"
	s.Save(r, w)
    */
    //email, ok := s.Values["email"] 

	t, err := text.ParseFiles(
		webPath("/templates/layout/header.html"), 
		webPath("/templates/layout/content.html"), 
		webPath("/templates/layout/footer.html"))

	if err != nil { 
		log.Fatal("Error %s", err)
	}

	fmt.Println("writing from new template")
	w.Header().Add("Content-Type", "text/html")

	err = t.ExecuteTemplate(w, "content", nil)
	if err != nil { 
		fmt.Println("Error: ", err)
		w.Write([]byte(fmt.Sprint(err))) 
        return err
	}
    return nil

	//reply( &w, "templates/index.amber", nil) //fmt.Fprintf(w, "Hello there")
}

func questionnaire(w http.ResponseWriter, r *http.Request){
	vars := mux.Vars(r)
	templateUID := vars["uid"]
	fmt.Println("TempalteUID: ", templateUID)

	w.Header().Add("Content-Type", "application/json")
	json.NewEncoder(w).Encode(backend.RegistrationQuestionnaire)
}



func addTemplate(w http.ResponseWriter, r *http.Request){
	err := backend.InsertTemplate(&backend.RegistrationQuestionnaire)

	fmt.Println(err)
	if err != nil{ fmt.Println("Couldn't insert RegistrationQuestionnaire") }

	fmt.Fprint(w, "Template saved")
}

func getTemplate(w http.ResponseWriter, r *http.Request){
	//t := backend.Template{}
	t, err := backend.GetTemplate("reg_questionnaire")
	//err := c.Find(bson.M{"uid":"reg_questionnaire"}).One(&t)//.One(&t)
	if err != nil{
		fmt.Println(err)
	}
	err = json.NewEncoder(w).Encode(t)
}

func updateTemplate(w http.ResponseWriter, r *http.Request){
	t, err := backend.GetTemplate("reg_questionnaire")
	if err != nil {
		fmt.Fprint(w, "Failed retrieving template with error: ", err)
		fmt.Println(err)
	}
	t.Desc = "updated description"
	t.Version = t.Version+1

	err =backend.UpdateTemplate(t)
	if err != nil{
		fmt.Fprint(w, "Template updated with error: ", err)
	}

	err = json.NewEncoder(w).Encode(t)
}




